<?php

declare(strict_types=1);

namespace App\Jobs;

use App\Services\MjzjCrawlerService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class CrawlMjzjData implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $timeout = 300;
    public int $tries = 3;
    private array $crawlParams;

    public function __construct(array $crawlParams)
    {
        $this->crawlParams = $crawlParams;
    }

    public function handle(MjzjCrawlerService $crawlerService): void
    {
        Log::info('开始执行MJZJ爬取任务', $this->crawlParams);

        try {
            if (isset($this->crawlParams['keywords']) && is_array($this->crawlParams['keywords'])) {
                $results = $crawlerService->crawlBatch(
                    $this->crawlParams['keywords'],
                    $this->crawlParams['batch_size'] ?? 20
                );
                
                Log::info('批量爬取完成', [
                    'keywords' => $this->crawlParams['keywords'],
                    'results_count' => count($results)
                ]);
            } else {
                $results = $crawlerService->searchReviewers($this->crawlParams);
                
                Log::info('单次爬取完成', [
                    'params' => $this->crawlParams,
                    'results_count' => count($results)
                ]);
            }
        } catch (\Exception $e) {
            Log::error('MJZJ爬取任务失败', [
                'params' => $this->crawlParams,
                'error' => $e->getMessage()
            ]);
            
            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('MJZJ爬取任务最终失败', [
            'params' => $this->crawlParams,
            'error' => $exception->getMessage()
        ]);
    }
}